package com.example.demo.zb;

import cn.hutool.core.util.StrUtil;
import com.example.demo.utils.JsonUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author linjingze
 * @date 2024/4/24 09:17
 */
public class GetZB {


    public static void main(String[] args) throws IOException {
        zb();
        // 获取当前日期
        LocalDate today = LocalDate.now();

        // 计算当前周的周五
        LocalDate thisFriday = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY));

        // 计算上周的周六
        // 先获取本周周一，然后倒退两天到上周的周六
        LocalDate lastMonday = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate lastSaturday = lastMonday.minusDays(2);

        // 输出结果
        System.out.println("今天的日期: " + today);
        System.out.println("这周的周五: " + thisFriday);
        System.out.println("上周的周六: " + lastSaturday);
    }

    public static void zb() throws IOException {
        CloseableHttpClient httpsClient = HttpsConnectionPool.getHttpsClient();
        CookieStore cookie = getCookie(httpsClient);
        // 创建POST请求
        Result file = getFile(cookie, httpsClient);
        String getFileUrlTmp = "http://www.tofba.com:8000/open/downloadFileByHttp?fileName={}&path=http://www.tofba.com:8080{}";
        //new
        HttpGet httpGet = new HttpGet(StrUtil.format(getFileUrlTmp, file.getData(), file.getMessage()));
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookie);
        CloseableHttpResponse response = httpsClient.execute(httpGet, context);
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();
        ExcelReader.newZhoubao(inputStream, "/Users/linjingze/Downloads/程乔玉工作");
    }

    private static Result getFile(CookieStore cookie, CloseableHttpClient httpsClient) throws IOException {
        HttpPost httpPost = new HttpPost("http://www.tofba.com:8000/api/consume/ajax?uri=/statistics/statementCenter/main&f=exportStatementDataFile&type=blank");

        // 设定时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // 获取当前日期的日历实例
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        // 查找当前周的周五
        // Calendar.DAY_OF_WEEK 的值 1 表示周日，7 表示周六
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
        String thisWeekFriday = sdf.format(calendar.getTime());

        // 查找上周的周六
        calendar.add(Calendar.WEEK_OF_YEAR, -1);
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
        String lastWeekSaturday = sdf.format(calendar.getTime());
        String json = StrUtil.format("{\n" +
                "    \"statementTemplateId\": \"2367\",\n" +
                "    \"seaairWaybillReportQuery\": {\n" +
                "        \"countryId\": [\n" +
                "            \"329\"\n" +
                "        ],\n" +
                "        \"rangeInStockDate\": [\n" +
                "            \"{}\",\n" +
                "            \"{}\"\n" +
                "        ]\n" +
                "    }\n" +
                "}", lastWeekSaturday, thisWeekFriday);
        // 设置请求体为JSON字符串
        StringEntity requestEntity = new StringEntity(json, StandardCharsets.UTF_8);
        httpPost.setEntity(requestEntity);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookie);
        CloseableHttpResponse response = httpsClient.execute(httpPost, context);
        // 读取响应内容
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        return JsonUtil.deserialize(responseString, Result.class);
    }

    private static CookieStore getCookie(CloseableHttpClient httpsClient) throws IOException {
        // 创建POST请求
        HttpPost httpPost = new HttpPost("http://www.tofba.com:8000/loginPost");
        // 构建JSON数据
        Map<String, Object> data = new HashMap<>();
        data.put("loginName", "11852");
        data.put("password", "Jayda967");
        // 使用Gson转换Map到JSON字符串
        String json = JsonUtil.serialize(data);
        HttpClientContext context = HttpClientContext.create();
        // 设置请求体为JSON字符串
        StringEntity requestEntity = new StringEntity(json, StandardCharsets.UTF_8);
        httpPost.setEntity(requestEntity);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        CloseableHttpResponse response = httpsClient.execute(httpPost, context);
// 读取响应内容
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        System.out.println("Response Content : " + responseString);

        // 从context中获取cookie
        List<Cookie> cookies = context.getCookieStore().getCookies();
        CookieStore cookieStore = new BasicCookieStore();
        for (Cookie cookie : cookies) {
            cookieStore.addCookie(cookie);
        }

        return cookieStore;
    }

}
